<!-- 标题背景的位置得改 -->
<template>
  <div class="w-full" :class="{
    'cursor-pointer': edit ?? true,
    'preview-block-active': (edit ?? true) && isActive
  }" :style="containerStyle" @click="handlePreviewClick">
    <section class="relative max-w-[1200px] mx-auto py-[16px] px-[32px]">
      <!-- 标题区域：根据对齐方式调整图片位置 -->
      <div :class="imageContainerClass" class="relative h-[42px]">
        <!-- 只有当有预览图片时才显示图片 -->
        <div v-if="previewTitleUrl && previewTitleUrl.trim() !== ''" class="relative inline-block">
          <img :src="previewTitleUrl" :alt="$t('competition.validation.titleBackground')"
            style="height: 42px; width: auto; max-width: none;" />
          <!-- 标题文字：垂直居中，水平位置根据对齐方式调整 -->
          <div v-if="data.titleInfo.title" :style="titleTextStyle" :class="titlePositionWithImageClass">
            {{ data.titleInfo.title }}
          </div>
        </div>
        <!-- 当没有背景图片时，文字根据对齐方式定位 -->
        <div v-else-if="data.titleInfo.title" :style="titleTextStyle" :class="titlePositionClass">
          {{ data.titleInfo.title }}
        </div>
      </div>
      <!-- 内容区域 -->
      <div v-if="data.content" class="mt-[32px]">
        <!-- 使用Markdown渲染器显示内容，支持图片正确展示 -->
        <MarkdownViewer :content="data.content" />
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { $t } from '#/locales'
import { getPreviewImageUrl } from './imagePreview'
import type { ContentState } from './content-module.vue'
import MarkdownViewer from '#/components/MarkdownViewer.vue';

interface Props {
  data: ContentState;
  edit?: boolean;
  isActive?: boolean;
}

const emit = defineEmits<{
  (e: 'click'): void;
}>()

const props = defineProps<Props>()

// 图片预览相关
const previewTitleUrl = ref<string>('')

// 图片预览相关函数（使用可复用工具函数）
async function loadImage(url: string) {
  if (!url) {
    return ''
  }

  try {
    const previewUrl = await getPreviewImageUrl(url)
    return previewUrl
  } catch (error) {
    console.error($t('competition.validation.imageLoadFailed'), error)
    return ''
  }
}

// 容器样式
const containerStyle = computed(() => {
  const styles: any = {
    // overflow: 'hidden'
  }
  styles.backgroundColor = props.data.bgColor || '#ffffff'
  return styles
})

// 图片容器对齐样式
const imageContainerClass = computed(() => {
  const textStyle = props.data.titleInfo.textStyle
  if (!textStyle) return 'flex justify-center'

  const alignCenter = textStyle.alignCenter

  switch (alignCenter) {
    case 'left':
      return 'flex justify-start'
    case 'right':
      return 'flex justify-end'
    case 'center':
    default:
      return 'flex justify-center'
  }
})

// 标题文字定位样式（仅在没有背景图片时使用）
const titlePositionClass = computed(() => {
  const textStyle = props.data.titleInfo.textStyle
  if (!textStyle) return 'absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 whitespace-nowrap'

  const alignCenter = textStyle.alignCenter
  const baseClasses = 'absolute top-1/2 transform -translate-y-1/2 whitespace-nowrap'

  switch (alignCenter) {
    case 'left':
      return `${baseClasses} left-0`
    case 'right':
      return `${baseClasses} right-0`
    case 'center':
    default:
      return `${baseClasses} left-1/2 -translate-x-1/2`
  }
})

// 标题文字定位样式（有背景图片时使用）
const titlePositionWithImageClass = computed(() => {
  const textStyle = props.data.titleInfo.textStyle
  if (!textStyle) return 'absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 whitespace-nowrap'

  const alignCenter = textStyle.alignCenter
  const baseClasses = 'absolute top-1/2 transform -translate-y-1/2 whitespace-nowrap'

  switch (alignCenter) {
    case 'left':
      // 距离图片左边缘24px
      return `${baseClasses} left-[24px]`
    case 'right':
      // 距离图片右边缘24px
      return `${baseClasses} right-[24px]`
    case 'center':
    default:
      // 水平居中
      return `${baseClasses} left-1/2 -translate-x-1/2`
  }
})

// 标题文字样式
const titleTextStyle = computed(() => {
  const textStyle = props.data.titleInfo.textStyle
  if (!textStyle) return {}

  return {
    fontSize: `${textStyle.fontSize || 16}px`,
    color: textStyle.fontColor || '#000000',
    fontWeight: textStyle.fontBold ? 'bold' : 'normal',
    fontStyle: textStyle.italic ? 'italic' : 'normal',
    textDecoration: textStyle.underline ? 'underline' : 'none',
    textAlign: (textStyle.alignCenter === 'center' ? 'center' :
      textStyle.alignCenter === 'right' ? 'right' : 'left') as 'left' | 'center' | 'right',
    width: textStyle.textWidth ? `${textStyle.textWidth}px` : 'auto',
    height: textStyle.textHeight ? `${textStyle.textHeight}px` : 'auto'
  }
})

// 预览区块点击事件处理
const handlePreviewClick = (event: Event) => {
  // 只在编辑模式下处理点击事件
  if (props.edit ?? true) {
    event.stopPropagation()
    emit('click')
  }
}

// 监听标题背景变化，自动加载预览
watch(() => props.data.titleInfo.titleUrl, async (newUrl) => {
  if (newUrl) {
    previewTitleUrl.value = await loadImage(newUrl)
  } else {
    // 当URL为空时，清除预览
    previewTitleUrl.value = ''
  }
}, { immediate: true })
</script>

<style scoped>
.title-bg img {
  transition: transform 0.3s ease;
}

/* 预览区块激活状态样式 */
.preview-block-active {
  border: 1px dashed #000000;
  transition: border 0.3s ease;
}
</style>
